package com.lcf.gateway.filter;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.lcf.base.exception.ExceptionEnum;
import com.lcf.base.model.R;
import com.lcf.base.utils.UrlUtils;
import com.lcf.gateway.config.TokenSkipUrlConfig;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 全局过滤器
 *
 * @author lcf
 */
@Component
public class SaTokenFilter implements GlobalFilter {
    private static final Logger log = LoggerFactory.getLogger(SaTokenFilter.class);
    @Resource
    private TokenSkipUrlConfig tokenSkipUrlConfig;

    /**
     * 内部服务外网隔离，使得请求只能通过网关访问，不能直接访问子服务
     * 为请求添加 Same-Token
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest newRequest = exchange
                .getRequest()
                .mutate()
                // 为请求追加 Same-Token 参数
                .header(SaSameUtil.SAME_TOKEN, SaSameUtil.getToken())
                .build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();

        return chain.filter(newExchange);
    }

    /**
     * 检查请求是否已登陆
     * 注册 [Sa-Token全局过滤器]
     */
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        //不检查token的路径
        List<String> urls = tokenSkipUrlConfig.getUrls();

        return new SaReactorFilter()
                // 指定 [拦截路由]
                /* 拦截所有path */
                .addInclude("/**")
                // 指定[认证函数]: 每次请求执行
                .setAuth(obj -> {
                    // 先放行 OPTIONS 请求
                    if ("OPTIONS".equals(SaHolder.getRequest().getMethod())) {
                        return;
                    }

                    // 不检查token的路径
                    if (UrlUtils.matchUrl(urls, SaHolder.getRequest().getRequestPath())) {
                        return;
                    }

                    // 登录校验 -- 拦截所有路由
                    SaRouter.match("/**", r -> StpUtil.checkLogin());
                })
                // 异常处理方法：每次setAuth函数出现异常时进入
                .setError(e -> {
                    log.error(e.getMessage(), e);

                    return JSONUtil.parse(R.fail(ExceptionEnum.NOT_LOGIN));
                });
    }
}

